<script setup>
import { ref, reactive, onMounted, computed } from "vue";
import { useConfigStore } from "@/store/modules/config";
import AppHeader from "@/components/app_header.vue";
import { showSuccessToast, showToast } from "vant";
import { useI18n } from "vue-i18n";
import Decimal from "decimal.js";
import { handleInput2 } from "@/utils";
import { isMobileDevice } from "@/utils/base_index";
import { useRouter } from "vue-router";
const router = useRouter();
const ToBlack = () => {
  router.push("transaction");
};
const useConfig = useConfigStore();
const { t } = useI18n();

const price = ref(null);
const quantity = ref(null);

const { locale } = useI18n();
const isShow = ref(false);
const loading = ref(false);
const finished = ref(false);
const isFocus = ref(false); //输入状态
const list = reactive([]);

////////
// 查询是否有订单存在
const isOrder = ref(true);
const loadData = async () => {
  const res = await useConfig.masterContract.methods
    .getTradeCurrent(useConfig.account)
    .call();
  const { sellAddress } = res;
  if (sellAddress === "0x0000000000000000000000000000000000000000") {
    isOrder.value = false;
  }
  console.log(res);
};
// 手续费
const totalFee = ref(0);
const getTotalFee = async () => {
  const fee = await useConfig.masterContract.methods
    .totalFee(useConfig.account)
    .call();
  totalFee.value = useConfig.web3.utils.toNumber(fee);
};

// 预支到合约
const estimatedArrival = computed(() => {
  // 卖出的数量+卖出的数量*手续费
  const _quantity = Number(quantity.value || 0);
  const _totalFee = totalFee.value / 100;
  return _quantity + _quantity * _totalFee;
});

// 收到
const arrival = computed(() => {
  try {
    const a = new Decimal(price.value);
    const b = new Decimal(quantity.value);
    const result = a.times(b);
    return result;
  } catch (error) {
    return "--";
  }
});
// 判断创建订单按钮状态
const getIsBtnDisabled = computed(() => {
  if (isOrder.value) return true;
  if (!quantity.value || Number(quantity.value) < 100) return true;
  if (!useConfig.balance || useConfig.balance < estimatedArrival.value) {
    return true;
  }
  return false;
});
// 是否输入了数量
const isAuantityEmpty = computed(() => {
  return !Boolean(Number(quantity.value));
});

// 创建
const createOrder = async () => {
  if (isOrder.value) return;
  if (getIsBtnDisabled.value) return;
  if (!price.value || !quantity.value) return;

  const _priceWei = useConfig.web3.utils.toWei(price.value, "ether");
  const _quantityWei = useConfig.web3.utils.toWei(quantity.value, "ether");

  const data = useConfig.masterContract.methods
    .sell(_priceWei, _quantityWei)
    .encodeABI();
  const params = {
    to: useConfig.masterContractAddress,
    from: useConfig.getAccount,
    value: useConfig.getWbe3.utils.toHex(0),
    data
  };
  try {
    const gasLimit = await useConfig.getWbe3.eth.estimateGas(params);
    params.gas = useConfig.getWbe3.utils.toHex(gasLimit);
  } catch (error) {
    // params.gas = useConfig.getWbe3.utils.toHex(200000);
  }
  useConfig.getWbe3.eth
    .sendTransaction(params)
    .on("transactionHash", function (hash) {
      console.log("hash", hash);
      showSuccessToast(t("bigv.success"));
    })
    .on("receipt", receipt => {
      console.log("receipt", receipt);
      loadData();
    })
    .catch(error => {
      showToast(error.data.message);
      console.error("error:", error.data);
    });

  console.log("创建订单");
};

onMounted(() => {
  getTotalFee();
  loadData();
  // checkingUSDT();
});
</script>

<template>
  <div class="home div-container">
    <!-- header--start-->
    <div class="div-header">
      <div class="div-left" @click.stop="ToBlack">
        <img src="@/assets/icon-black.png" alt="" />
      </div>
      <span class="title">
        <img src="@/assets/icon-logo.png" width="40" alt="" />
      </span>
      <div class="div-right">...</div>
    </div>
    <!-- header--start-->
    <!-- div-wallet--start-->
    <AppHeader />
    <!--    <div class="div-wallet">-->
    <!--      <div class="wallet" @click.stop="showDialog">-->
    <!--        <img src="@/assets/icon-wallet.png" width="32" height="32" alt="">-->
    <!--        0x02****27078d9d-->
    <!--      </div>-->
    <!--      <div class="div-change" @click="changeLang">-->
    <!--        <img src="@/assets/icon-change.png" width="19" height="19" alt="">-->
    <!--        {{$t('home.ch')}}-->
    <!--      </div>-->
    <!--    </div>-->

    <div class="div-record">
      <div class="div-record-title">{{ $t("transaction.createOrder") }}</div>
    </div>
    <!--购买ESC -->
    <div class="div-record">
      <div class="div-list div-buy-list">
        <!--        {{ useConfig.balance }}-->
        <div class="div-buy-title">
          {{ $t("exchange.buy") }} {{ useConfig.name }}
        </div>
        <van-list>
          <van-cell>
            <span>
              <img
                src="./../../assets/icon-exchange-blance.png"
                width="19"
                alt=""
              />
              {{ useConfig.balance || "--" }} {{ useConfig.name || "--" }}
            </span>
            <span>{{ $t("exchange.blance") }}</span>
          </van-cell>

          <div class="div-quantity">
            <p>{{ $t("transaction.price") }}</p>
            <div class="div-input">
              <van-field
                v-model="price"
                type="number"
                :border="false"
                :placeholder="$t('transaction.pleaseEnterPrice')"
                :class="isFocus ? 'focus-style' : ''"
                :formatter="handleInput2"
                @focus="isFocus = true"
                @blur="isFocus = false"
              />
              <span class="unit">USDT</span>
            </div>
          </div>

          <div class="div-quantity">
            <p>{{ $t("exchange.quantity") }}</p>
            <div class="div-input">
              <van-field
                v-model="quantity"
                type="digit"
                :border="false"
                :placeholder="$t('transaction.pleaseEnterQuantity')"
                :class="isFocus ? 'focus-style' : ''"
                @focus="isFocus = true"
                @blur="isFocus = false"
              />
              <span class="unit">{{ useConfig.name }}</span>
            </div>
          </div>

          <van-cell>
            <span :class="{ 'font-gold': !isAuantityEmpty }">
              {{ isAuantityEmpty ? "--" : totalFee + "%" }}
            </span>
            <span>{{ $t("transaction.fee") }}</span>
          </van-cell>

          <van-cell>
            <span :class="{ 'font-gold': !isAuantityEmpty }">
              {{
                isAuantityEmpty ? "--" : estimatedArrival + " " + useConfig.name
              }}
            </span>
            <span>{{ $t("transaction.advancePayment") }} </span>
          </van-cell>

          <van-cell>
            <span :class="{ 'font-gold': !isAuantityEmpty }">
              {{ isAuantityEmpty ? "--" : arrival + "  USDT" }}
            </span>
            <span>{{ $t("transaction.receive") }}</span>
          </van-cell>
        </van-list>
      </div>
    </div>

    <div
      class="div-btn div-buy-btn"
      :class="getIsBtnDisabled ? 'btn-disabled' : ''"
      @click="createOrder"
    >
      {{ $t("transaction.createOrder") }}
    </div>

    <div class="div-order-des">
      <p class="title">{{ $t("transaction.title") }}</p>
      <p>{{ $t("transaction.des1") }}</p>
      <p>{{ $t("transaction.des2") }}</p>
      <p>{{ $t("transaction.des3") }}</p>
      <p>{{ $t("transaction.des4") }}</p>
      <p>{{ $t("transaction.des5") }}</p>
    </div>
  </div>
</template>

<style scoped lang="less">
@import "./../../styles/mixin.less";
p {
  margin: 0px;
}
.home {
  font-size: 14px;
  color: #ffffff;
  padding-bottom: 20px;
}

.div-wallet {
  height: 44px;
  padding: 0 14px;
  display: flex;
  font-size: 14px;
  justify-content: space-between;
  & > div {
    display: flex;
    align-items: center;
    gap: 10px;
  }
  .wallet {
    padding-left: 10px;
    padding-right: 10px;
    border-radius: 20px;
    border: 1px solid #9cb3bf;
  }
}
.div-record {
  padding: 0 14px;
  position: relative;
  &-title {
    font-weight: 500;
    font-size: 23px;
    color: #e5f0f4;
    line-height: 40px;
    text-indent: 14px;
    position: relative;
    margin-bottom: 18px;
    margin-top: 20px;
    &:before {
      display: block;
      content: "";
      width: 5px;
      height: 23px;
      position: absolute;
      left: 0px;
      top: 8px;
      background: #47ddc2;
      border-radius: 5px;
    }
  }

  .div-list {
    padding: 22px 20px;
    background: #27283e;
    border-radius: 20px;
    border: 1px solid #47ddc2;
    opacity: 0.99;
    :deep(.van-cell) {
      background: #2e2f4a;
      color: #e5f0f4;
      height: 50px;
      margin-bottom: 18px;
    }
    .margin-bottom-0 {
      margin-bottom: 0;
    }
    :deep(.van-cell:after) {
      display: none;
    }
    :deep(.van-cell__value) {
      display: flex;
      justify-content: space-between;
      align-items: center;
      span:nth-child(1) {
        font-weight: 500;
        font-size: 14px;
        color: #fff;
        line-height: 20px;
        display: flex;
        align-items: center;
        gap: 6px;
      }
      span:nth-child(2) {
        font-size: 12px;
        color: #606374;
        font-weight: 500;
      }
    }
    .font-gold {
      color: #ffca63 !important;
    }
  }
  .div-buy-list {
    border: 1px solid #62737f;
    .div-buy-title {
      margin-bottom: 21px;
      font-weight: 500;
      font-size: 18px;
      color: #e5f0f4;
    }
    .div-quantity {
      & > p {
        font-size: 12px;
        line-height: 16px;
        color: #606374;
      }
    }

    :deep(.van-field) {
      margin: 0 auto 16px;
      border-bottom: 1px solid #e5f0f4;
      padding-left: 0px;
      background: none;
      .van-field__control {
        color: #fff;
        font-size: 14px;
      }
      &.focus-style {
        border-bottom: 1px solid #0064fb;
      }
    }
    .div-input {
      position: relative;
      .unit {
        position: absolute;
        right: 10px;
        bottom: 12px;
        color: #0065fc;
        font-weight: bold;
        font-size: 14px;
      }
    }
  }
  .div-quantity {
    .enterAddress {
      font-weight: 500;
      font-size: 14px;
      color: #e5f0f4;
      line-height: 20px;
      background-color: #27283e;
      padding-left: 0px;
      padding-right: 0px;
      :deep(.van-field__control) {
        color: #fff;
      }
    }
    :deep(.van-cell:after) {
      left: 0px;
    }
  }
}
.div-buy-btn {
  margin: 20px 12px 10px;
  display: flex;
  align-items: center;
  width: calc(100% - 24px);
  justify-content: center;
  height: 56px;
  font-size: 16px;
  color: #fff;
  border-radius: 16px;
  background: #0066ff;
  &.btn-disabled {
    background-color: #3e436c;
    color: #5e6486;
  }
}
.div-auth-btn {
  margin: 20px 12px 10px;
  display: flex;
  align-items: center;
  width: calc(100% - 24px);
  justify-content: center;
  height: 56px;
  font-size: 16px;
  color: #151d24;
  font-weight: 500;
  border-radius: 16px;
  background: linear-gradient(57deg, #47ddc2 0%, #c1ffc8 100%);
}
.div-order-des {
  padding: 10px 12px;
  p {
    font-weight: 500;
    font-size: 13px;
    color: #606374;
    line-height: 18px;
    text-align: left;
    font-style: normal;
  }
  .title {
    font-weight: 500;
    font-size: 18px;
    color: #e5f0f4;
    line-height: 26px;
    padding-bottom: 13px;
  }
}
</style>
